<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');

class simage extends CI_Model {
    private $file;
    private $image;
    private $info;
	private $cache_patch = 'images';
	public function __construct() {
		 
	}
	public function cache($file = '', $name = '')
	{
		if (file_exists($file)) {
			if($name !=''){
				$this->run_cache($file);
			}
			else {
				$image_size = $this->config->item("IMAGE_SIZE");
				if(isset($image_size)){
					foreach($image_size as $kname =>$size){
						if(isset($size[0])&& isset($size[1]))
							$this->run_cache($file,$size[0],$size[1]);
					}
				}
			}
			
    	} else {
      		return $this->template->url_page.$file;
    	}
	}
	
	public function run_cache($file = '', $width = '', $height ='')
	{
		$dir_cache = $this->create_dirs($file);
		$file_name = basename($file);
		$full_patch = $dir_cache.$width."x".$height."-".$file_name;
		$config['image_library'] = 'gd2';
		$config['source_image']	= "./".$file;
		$config['new_image'] = $full_patch;
		//$config['create_thumb'] = TRUE;
		$config['maintain_ratio'] = TRUE;
		$config['width']	 = $width;
		$config['height']	= $height;

		$this->load->library('image_lib', $config); 
		$this->image_lib->initialize($config);
		if(!$this->image_lib->resize())
			return $this->template->url_page.$file;
		return $this->template->url_page.$config['new_image'];
    	
	}
	
	function create_dirs($file =''){
	$dir_paths = explode("/",str_replace("dataupload",$this->cache_patch,$file));
	$dir = "";
	for($i=0; $i<count($dir_paths) -1; $i++){
		$dir_path = $dir_paths[$i];
		$dir.= $dir_path."/";
		if (!is_dir($dir)) {
			mkdir($dir);
			chmod($dir, 0777);
		}
	}
	return $dir;
	}
	
	function delete($full_patch =''){
		if (file_exists($full_patch)) {
			$name_file = basename($full_patch);
			$patch = str_replace($name_file,"",$full_patch);
			$patch = str_replace("dataupload/",$this->cache_patch."/",$patch);
			$files = glob($patch."*x*-".$name_file);
			foreach($files as $file){
			  if(is_file($file)){
				 unlink($file);
			  }
			}
   			return true;
		}
		return false;
	}
}
?>